package com.example.criminalintent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import org.json.JSONException;

import android.content.Context;
import android.util.Log;

public class CrimeLab {
	private static CrimeLab sCrimeLab;
	private Context mAppContext;
	private ArrayList<Crime>  mCrimes;
	
	private static final String  FILENAME= "crime.json";
	private CriminalIntentJSONSerializer mSerializer;
	
	public static CrimeLab get(Context c){
		if(sCrimeLab == null){
			sCrimeLab = new CrimeLab(c.getApplicationContext());
		}
		return sCrimeLab;
	}
	
	private CrimeLab(Context c){
		mAppContext = c;
//		mCrimes = new ArrayList<Crime>();
		mSerializer = new CriminalIntentJSONSerializer(c, FILENAME);
		
		try{
			mCrimes = mSerializer.loadCrimes();
		}catch(Exception e){
			Log.e("CrimeLab", ""+e);
		}
//		for(int i = 0; i < 100; i++){
//			Crime crime = new Crime();
//			crime.setTitle("Crime #"+i);
//			crime.setSolved(i % 2 == 0);
//			mCrimes.add(crime);
//		}
	}
	
	public void addCrime(Crime c){
		mCrimes.add(c);
	}

	public ArrayList<Crime> getCrimes() {
		return mCrimes;
	}
	
	public Crime getCrime(UUID id){
		for(Crime c:mCrimes){
			if(c.getId().equals(id)){
				return c;
			}
		}
		return null;
	}
	
	public boolean saveCrimes(){
		try {
			mSerializer.saveCrimes(mCrimes);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}


}
